package com.njsf.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.njsf.annotation.Token;
import com.njsf.dto.ResponseJson;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

public class TokenInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    private ResponseJson responseJson = new ResponseJson(101,"不能重复提交数据!");

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String jsonStr = objectMapper.writeValueAsString(responseJson);
        response.setCharacterEncoding("UTF-8");
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Token.class)){
                Token token = method.getAnnotation(Token.class);
                if (token.create()){
                    String tokenStr = UUID.randomUUID().toString();
                    request.setAttribute("token",tokenStr);
                    request.getSession().setAttribute("token",tokenStr);
                    return true;
                }
                if (token.remove()){
                    String clientToken = request.getHeader("token");
                    if (clientToken == null){
                        response.getWriter().write(jsonStr);
                        return false;
                    }
                    Object serverToken = request.getSession().getAttribute("token");
                    if (serverToken == null){
                        response.getWriter().write(jsonStr);
                        return false;
                    }
                    if (!clientToken.equals(serverToken)){
                        response.getWriter().write(jsonStr);
                        return false;
                    }
                    request.getSession().removeAttribute("token");
                    return true;
                }
            }
        }
        return true;
    }
}
